package titt.util;

import java.lang.reflect.Array;

public class ArrayUtil {
		
	public static <T> void copyTo(T src, int fromSourceIndex, T dest, int fromDestIndex, int length) {
		System.arraycopy(src, fromSourceIndex, dest, fromDestIndex, length);
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T combine(T array_1, T array_2) {
		int len1 = Array.getLength(array_1), len2 = Array.getLength(array_2);
		T t = (T)Array.newInstance(array_1.getClass().getComponentType(), len1 + len2);
		
		copyTo(array_1, 0, t, 0, len1);
		copyTo(array_2, 0, t, len1, len2);

		return t;
	}

	@SuppressWarnings("unchecked")
	public static <T> T combine(T... arrays) {
		int len = 0;
		for(int i = 0; i < Array.getLength(arrays); i++) len += Array.getLength(Array.get(arrays, i));
		T t = (T)Array.newInstance(arrays.getClass().getComponentType().getComponentType(), len);

		int from = 0;
		for(int i = 0; i < Array.getLength(arrays); i++) {
			copyTo(Array.get(arrays, i), 0, t, from, Array.getLength(Array.get(arrays, i)));
			from += Array.getLength(Array.get(arrays, i));
		}

		return t;
	}

	@SuppressWarnings("unchecked")
	public static <S,T> T[] convert(S[] arr, Converter<S, T> c) throws Exception {
		T[] os = (T[])Array.newInstance(c.getClass().getMethods()[0].getReturnType(), arr.length);
		convertTo(arr,os,c);
		return os;
	}

	public static <S,T> T[] convertTo(S[] sarr, T[] tarr, Converter<S, T> c) {
		for(int i = 0; i < tarr.length; i++)
			tarr[i] = c.convert(sarr[i]);

		return tarr;
		
	}
}
